package com.androidified.personalshopper.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;

import android.content.Context;

import com.google.gson.Gson;

public class CacheModel {

	public static boolean store(Context context, String fileName, Object content) {
		File cache = new File(context.getCacheDir(), fileName);
		
		if (!cache.exists()) {
			try {
				cache.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		
		try {
			Gson gson = new Gson();
			String str = gson.toJson(content);
			FileWriter fw = new FileWriter(cache);
			fw.append(str);
			fw.flush();
			fw.close();
			return true;
			
		} catch (IOException e) {
			e.printStackTrace();
		}
				
		return false;
	}
	
	public static <T> T retrieve(Context context, String fileName, Type type) {
		File cache = new File(context.getCacheDir(), fileName);
		
		if (cache.exists()) {
			try {
				BufferedReader reader = new BufferedReader(new FileReader(cache));
				String line, results = "";
				while ((line = reader.readLine()) != null) {
					results += line;
				}
				reader.close();
				Gson gson = new Gson();
				return gson.fromJson(results, type);
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
				
		return null;
	}
	
}
